/*
 * Copyright 2010 Eligio Colutta
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * http://www.apache.org/licenses/LICENSE-2.0 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 */
package com.google.code.p2pxmppclient.notifyserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.Socket;
import java.util.logging.Logger;

import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;

import com.google.code.p2pxmppclient.Configurer;

/**
 * 
 * @author eliosh
 * @version $Rev$
 * @lastautorcommit $Author$
 * @lastdatecommit $Date$
 */
public class NotifyServerThread extends Thread {
	private Socket socket = null;
	private XMPPConnection conn;
	private static final Logger log = Logger.getLogger(NotifyServerThread.class.getCanonicalName());

	public NotifyServerThread(XMPPConnection connection, Socket socket) {
		super("NotifyServerThread");
		this.socket = socket;
		this.conn = connection;
	}

	public void run() {
		try {
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

			String message = in.readLine();
			log.info("Message received: " + message);
			for (String recipient : Configurer.getRecipients()) {
				sendMessage(recipient, message);
			}
			out.write("OK");
			out.close();
			in.close();
			socket.close();

		} catch (IOException e) {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			e.printStackTrace(pw);
			log.warning(sw.toString());
		}
	}

	private void sendMessage(String recipient, String message){
		Roster roster = conn.getRoster();
		Presence presence = roster.getPresence(recipient);
		if (presence.getType() == Presence.Type.available) {
			Message reply = new Message();
			reply.setTo(recipient);
			reply.setBody(message);
			conn.sendPacket(reply);
			log.info(recipient + " available. Message sent.");
		}else{
			// put in queue
			NotifyServer.addOfflineNotification(recipient, message);
			log.info(recipient + " not available. Put in queue for later sending.");
		}
	}	
	
}
